package com.hmdp.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 */
@Slf4j
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result queryTypeList() {
        String tokenKey = RedisConstants.CACHE_SHOP_TYPE_KEY;

        // 查询 Redis 是否存在，存在即返回，不存在则去 MySQL 中查询
        String cacheShopType = stringRedisTemplate.opsForValue().get(tokenKey);
        if (StrUtil.isNotBlank(cacheShopType)) {
            List<ShopType> typeList = JSONUtil.toList(cacheShopType, ShopType.class);
            log.info("Redis: ShopType List is Hit!");
            return Result.ok(typeList);
        }

        List<ShopType> typeList = query().orderByAsc("sort").list();
        log.info("Redis: ShopType List is Miss!");

        // 若 MySQL 中不存在则返回错误；存在，则加入到缓存，
        if (typeList == null) {
            return Result.fail("ShopType List Loaded Error!");
        }

        String typeJsonStr = JSONUtil.toJsonStr(typeList);
        stringRedisTemplate.opsForValue().set(tokenKey, typeJsonStr, RedisConstants.CACHE_SHOP_TYPE_TTL, TimeUnit.DAYS);

        log.info("MySQL: ShopType List is Hit!");

        return Result.ok(typeList);
    }
}
